<template>
  <div class="position-container">
    <div class="page-header">
      <h2>职位管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增职位
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="职位名称">
          <el-input v-model="searchForm.name" placeholder="请输入职位名称" clearable />
        </el-form-item>
        <el-form-item label="职位编码">
          <el-input v-model="searchForm.code" placeholder="请输入职位编码" clearable />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-tree-select
            v-model="searchForm.departmentId"
            :data="departmentOptions"
            :props="{ children: 'children', label: 'name' }"
            check-strictly
            node-key="id"
            placeholder="请选择部门"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" label="#" />
        <el-table-column prop="name" label="职位名称" min-width="120" />
        <el-table-column prop="code" label="职位编码" min-width="120" />
        <el-table-column prop="departmentName" label="所属部门" min-width="120" />
        <el-table-column prop="description" label="职位描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleToggleStatus(scope.row)"
            >
              <el-icon><CircleCheck v-if="scope.row.status === 0" /><CircleClose v-else /></el-icon>
              {{ scope.row.status === 0 ? '启用' : '禁用' }}
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleDelete(scope.row)"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 职位表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增职位' : '编辑职位'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="positionFormRef"
        :model="positionForm"
        :rules="positionFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="所属部门" prop="departmentId">
          <el-tree-select
            v-model="positionForm.departmentId"
            :data="departmentOptions"
            :props="{ children: 'children', label: 'name' }"
            check-strictly
            node-key="id"
            placeholder="请选择部门"
          />
        </el-form-item>
        <el-form-item label="职位名称" prop="name">
          <el-input v-model="positionForm.name" placeholder="请输入职位名称" />
        </el-form-item>
        <el-form-item label="职位编码" prop="code">
          <el-input v-model="positionForm.code" placeholder="请输入职位编码" />
        </el-form-item>
        <el-form-item label="职位描述" prop="description">
          <el-input 
            v-model="positionForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入职位描述" 
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="positionForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="positionForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Search, 
  Refresh, 
  Edit, 
  Delete, 
  CircleCheck, 
  CircleClose 
} from '@element-plus/icons-vue'

// 表单引用
const positionFormRef = ref(null)

// 表格加载状态
const tableLoading = ref(false)

// 对话框状态
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  departmentId: '',
  status: ''
})

// 职位表单
const positionForm = reactive({
  id: '',
  departmentId: '',
  name: '',
  code: '',
  description: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const positionFormRules = {
  departmentId: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入职位名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入职位编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9_]+$/, message: '职位编码只能包含大写字母、数字和下划线', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 部门选项
const departmentOptions = ref([
  {
    id: 1,
    name: '总公司',
    children: [
      {
        id: 2,
        name: '信息技术部'
      },
      {
        id: 3,
        name: '运输部',
        children: [
          {
            id: 6,
            name: '调度组'
          },
          {
            id: 7,
            name: '车队管理组'
          }
        ]
      },
      {
        id: 4,
        name: '财务部'
      },
      {
        id: 5,
        name: '客服部'
      }
    ]
  }
])

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '总经理',
    code: 'GM',
    departmentId: 1,
    departmentName: '总公司',
    description: '负责公司整体运营和战略决策',
    sort: 1,
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 2,
    name: 'IT经理',
    code: 'IT_MGR',
    departmentId: 2,
    departmentName: '信息技术部',
    description: '负责公司IT系统规划和管理',
    sort: 2,
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 3,
    name: '高级开发工程师',
    code: 'SR_DEV',
    departmentId: 2,
    departmentName: '信息技术部',
    description: '负责系统架构设计和核心功能开发',
    sort: 3,
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 4,
    name: '开发工程师',
    code: 'DEV',
    departmentId: 2,
    departmentName: '信息技术部',
    description: '负责系统功能开发和维护',
    sort: 4,
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 5,
    name: '运输经理',
    code: 'TRANS_MGR',
    departmentId: 3,
    departmentName: '运输部',
    description: '负责运输部门整体管理',
    sort: 5,
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 6,
    name: '调度主管',
    code: 'DISP_SUP',
    departmentId: 6,
    departmentName: '调度组',
    description: '负责车辆调度管理',
    sort: 6,
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 7,
    name: '调度员',
    code: 'DISP',
    departmentId: 6,
    departmentName: '调度组',
    description: '负责日常车辆调度',
    sort: 7,
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 8,
    name: '车队主管',
    code: 'FLEET_SUP',
    departmentId: 7,
    departmentName: '车队管理组',
    description: '负责车队管理',
    sort: 8,
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 9,
    name: '财务经理',
    code: 'FIN_MGR',
    departmentId: 4,
    departmentName: '财务部',
    description: '负责公司财务管理',
    sort: 9,
    status: 1,
    createTime: '2025-01-01 00:00:00'
  },
  {
    id: 10,
    name: '会计',
    code: 'ACCT',
    departmentId: 4,
    departmentName: '财务部',
    description: '负责财务核算和报表',
    sort: 10,
    status: 0,
    createTime: '2025-01-01 00:00:00'
  }
])

// 加载职位列表
const loadPositionList = async () => {
  tableLoading.value = true
  try {
    // 实际项目中应该调用API获取职位列表
    // const { data } = await getPositionList({
    //   ...searchForm,
    //   page: pagination.currentPage,
    //   pageSize: pagination.pageSize
    // })
    // tableData.value = data.list
    // pagination.total = data.total
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 使用模拟数据
    let filteredData = [...tableData.value]
    
    // 根据搜索条件过滤
    if (searchForm.name) {
      filteredData = filteredData.filter(item => item.name.includes(searchForm.name))
    }
    if (searchForm.code) {
      filteredData = filteredData.filter(item => item.code.includes(searchForm.code))
    }
    if (searchForm.departmentId) {
      filteredData = filteredData.filter(item => item.departmentId === searchForm.departmentId)
    }
    if (searchForm.status !== '') {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    pagination.total = filteredData.length
    
  } catch (error) {
    console.error('加载职位列表失败:', error)
    ElMessage.error('加载职位列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadPositionList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadPositionList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadPositionList()
}

// 新增职位
const handleAdd = () => {
  dialogType.value = 'add'
  resetPositionForm()
  dialogVisible.value = true
}

// 编辑职位
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetPositionForm()
  
  // 填充表单数据
  positionForm.id = row.id
  positionForm.departmentId = row.departmentId
  positionForm.name = row.name
  positionForm.code = row.code
  positionForm.description = row.description
  positionForm.sort = row.sort
  positionForm.status = row.status
  
  dialogVisible.value = true
}

// 启用/禁用职位
const handleToggleStatus = (row) => {
  const action = row.status === 1 ? '禁用' : '启用'
  const newStatus = row.status === 1 ? 0 : 1
  
  ElMessageBox.confirm(
    `确定要${action}职位 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 实际项目中应该调用API更新职位状态
        // await updatePositionStatus({
        //   positionId: row.id,
        //   status: newStatus
        // })
        
        // 更新本地数据
        row.status = newStatus
        
        ElMessage.success(`${action}职位成功`)
      } catch (error) {
        console.error(`${action}职位失败:`, error)
        ElMessage.error(`${action}职位失败`)
      }
    })
    .catch(() => {})
}

// 删除职位
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除职位 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 实际项目中应该调用API删除职位
        // await deletePosition(row.id)
        
        // 更新本地数据
        const index = tableData.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          tableData.value.splice(index, 1)
          pagination.total--
        }
        
        ElMessage.success('删除职位成功')
      } catch (error) {
        console.error('删除职位失败:', error)
        ElMessage.error('删除职位失败')
      }
    })
    .catch(() => {})
}

// 重置职位表单
const resetPositionForm = () => {
  Object.keys(positionForm).forEach(key => {
    if (key === 'status') {
      positionForm[key] = 1
    } else if (key === 'sort') {
      positionForm[key] = 0
    } else {
      positionForm[key] = ''
    }
  })
  
  if (positionFormRef.value) {
    positionFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!positionFormRef.value) return
  
  await positionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 获取部门名称
        let departmentName = ''
        const findDepartment = (departments, id) => {
          for (const dept of departments) {
            if (dept.id === id) {
              return dept.name
            }
            if (dept.children && dept.children.length > 0) {
              const name = findDepartment(dept.children, id)
              if (name) return name
            }
          }
          return null
        }
        departmentName = findDepartment(departmentOptions.value, positionForm.departmentId) || ''
        
        if (dialogType.value === 'add') {
          // 实际项目中应该调用API添加职位
          // const { data } = await addPosition(positionForm)
          
          // 模拟添加职位
          const newPosition = {
            id: Date.now(),
            departmentId: positionForm.departmentId,
            departmentName,
            name: positionForm.name,
            code: positionForm.code,
            description: positionForm.description,
            sort: positionForm.sort,
            status: positionForm.status,
            createTime: new Date().toLocaleString()
          }
          
          tableData.value.push(newPosition)
          pagination.total++
          
          ElMessage.success('添加职位成功')
        } else {
          // 实际项目中应该调用API更新职位
          // await updatePosition(positionForm)
          
          // 更新本地数据
          const index = tableData.value.findIndex(item => item.id === positionForm.id)
          if (index !== -1) {
            tableData.value[index] = {
              ...tableData.value[index],
              departmentId: positionForm.departmentId,
              departmentName,
              name: positionForm.name,
              code: positionForm.code,
              description: positionForm.description,
              sort: positionForm.sort,
              status: positionForm.status
            }
          }
          
          ElMessage.success('更新职位成功')
        }
        
        dialogVisible.value = false
      } catch (error) {
        console.error('保存职位失败:', error)
        ElMessage.error('保存职位失败')
      }
    }
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadPositionList()
})
</script>

<style scoped>
.position-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
